import axios from 'axios'
import router from '../../router'
import {
  Notification
} from 'element-ui'


axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response;
}, error => {
  // 对响应错误做点什么
  if (error.response.status === 401) {
    router.push({
      path: '/',
      query: {
        error: 'login'
      }
    })
  }
  return Promise.reject(error);
});

async function ajax(param) {
  try {
    const type = param.type.toLowerCase();
    const result = {
      method: type,
      url: param.url,
      params: {},
      headers: {
        token: sessionStorage.getItem('access_token') || '',
        ...(param.header || {}),
      },
      ...(param.config || {}),
    };
    if (param.params) {
      if (param.dataType) {
        result[param.dataType] = param.params
      } else {
        if (['get', 'delete'].includes(type)) {
          // let restfulUrl = param.url;
          // const params = param.params || [];
          // const arr = typeof params !== 'object' ? [params] : params;
          // arr.forEach((item) => {
          //   restfulUrl += `?${item}`;
          // });
          // result.url = restfulUrl;
          result.params = param.params
        } else {
          result.data = param.params;
        }
      }
    }
    const res = await axios(result);
    if (res.data.code === 0 || res.data.code === 1 || res.data.code === 200) {
      return res.data || {};
    } else if (['40001', '40002'].includes(res.data.code)) {
      router.push({
        path: '/',
        query: {
          error: 'login'
        }
      })
    } else {
      Notification.warning({
        title: '提示',
        message: res.data.msg || res.data.message
      });
      return res.data;
    }
  } catch (e) {
    if (axios.isCancel(e)) {
      return null;
    }
    if (!String(e).includes('401'))
      Notification.error({
        title: '提示',
        message: '网络异常'
      });
    return null;
  }
}

export {
  ajax,
};
export default {
  install(Vue) {
    Object.defineProperty(Vue.prototype, '$ajax', {
      value: ajax
    });
  },
};